﻿Option Strict On
Option Explicit On
Option Infer On

Imports System
Imports System.Linq
Imports System.Xml.Linq


Public Module XmlExtensions

   <System.Runtime.CompilerServices.Extension()> _
   Public Function GetString(ByVal attribute As XAttribute) As String
      If attribute Is Nothing Then
         Return Nothing
      End If
      Return attribute.Value
   End Function

   <System.Runtime.CompilerServices.Extension()> _
   Public Function GetStringOrEmpty(ByVal attribute As XAttribute) As String
      If attribute Is Nothing Then
         Return String.Empty
      End If
      Return attribute.Value
   End Function

   ''' <summary>
   ''' Adds a new attribute to an Xelement via a function for use in Linq statements
   ''' </summary>
   ''' <param name="xElement">The element to add the name to</param>
   ''' <param name="attributeName">The name of the attribute</param>
   ''' <param name="value">The value of the attribute</param>
   ''' <returns>A dummy value that is always true</returns>
   ''' <remarks></remarks>
   <System.Runtime.CompilerServices.Extension()> _
  Public Function AddAttribute( _
            ByVal xElement As XElement, _
            ByVal attributeName As XName, _
            ByVal value As String) _
            As Boolean
      xElement.Add(New XAttribute(attributeName, value))
      Return True
   End Function

   <System.Runtime.CompilerServices.Extension()> _
   Public Function AddAttributes( _
            ByVal xElementTarget As XElement, _
            ByVal xElementSource As XElement) _
            As XElement
      For Each attr In xElementSource.Attributes
         xElementTarget.Add(New XAttribute(attr.Name, attr.Value))
      Next
      Return xElementTarget
   End Function

   <System.Runtime.CompilerServices.Extension()> _
   Public Function FirstAncestor( _
            ByVal target As XElement, _
            ByVal name As XName) _
            As XElement
      Return target.Ancestors(name).FirstOrDefault
   End Function

   <System.Runtime.CompilerServices.Extension()> _
   Public Function FirstAncestor( _
            ByVal target As XElement, _
            ByVal nSpace As XNamespace, _
            ByVal name As String) _
            As XElement
      Return target.Ancestors(name).FirstOrDefault
   End Function

End Module
